package com.example.appalumaj;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

public class SimpleAdapter extends ArrayAdapter{

	private ArrayList<Uri> items;

	@SuppressWarnings("unchecked")
	public SimpleAdapter(Context context, int textViewResourceId,
			ArrayList<Uri> items) {
		super(context, textViewResourceId, items);
		this.items = items;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.activity_main5, null);
		}

		if (items != null) {
			ImageView imagen = (ImageView) v.findViewById(R.id.imageView1);
			
			if (imagen != null) {
				imagen.setImageDrawable(cargaImagen(items.get(position)+""));
			}			

		}

		return v;

	}
	
	private Drawable cargaImagen(String url) {
		try {
			final URLConnection conn = new URL(url).openConnection();
			conn.connect();
			final InputStream is = conn.getInputStream();

			final BufferedInputStream bis = new BufferedInputStream(is, 100000);
			Bitmap bitmap = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
			Drawable drawable = new BitmapDrawable(redimensionarImagenMaximo(bitmap, bitmap.getWidth()/2, bitmap.getHeight()/2));
			return drawable;
		} catch (Exception e) {
			return null;
		}
	}
	
	public Bitmap redimensionarImagenMaximo(Bitmap mBitmap, float newWidth, float newHeigth){
		   //Redimensionamos
		   int width = mBitmap.getWidth();
		   int height = mBitmap.getHeight();
		   float scaleWidth = ((float) newWidth) / width;
		   float scaleHeight = ((float) newHeigth) / height;
		   // create a matrix for the manipulation
		   Matrix matrix = new Matrix();
		   // resize the bit map
		   matrix.postScale(scaleWidth, scaleHeight);
		   // recreate the new Bitmap
		   return Bitmap.createBitmap(mBitmap, 0, 0, width, height, matrix, false);
		}

}